/** 
 * @CopyRight (c) 2012-2012
 * @Company <江苏瑞德信息技术有限公司>
 * @Project <eshop>
 * @JDK_Version_Used:<JDK1.6>
 * @Description:TODO<描述用途>
 * @Title: MemberWeb.java
 * @Author: <何俊>
 * @Author_of_Contact <E:azj1001@sina.com T:18651831939>
 * @Date 2012-11-13 下午3:00:42
 * @Modified_By: <修改人>
 * @Modified_of_Contact <修改人联系方式>
 * @Modified_Date <修改日期时间>
 * @Why & What is modified <修改原因描述>
 * @Version v1.00
 */
package com.e.buy.web.back.manager;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.commons.query.ConditionBean;
import cn.commons.query.exception.AzjQueryBuilderException;

import com.e.buy.BuyTools;
import com.e.buy.bean.Toolbar;
import com.e.buy.bean.Tree;
import com.e.buy.bean.back.manager.CmiAdminUser;
import com.e.buy.bean.back.manager.cmi_power.CmiRole;
import com.e.buy.enums.Commons;
import com.e.buy.enums.Status;
import com.e.buy.service.CommonsServiceClient;

/**
 * @Description:TODO(描述类别作用)
 * @author <何俊>
 * @date 2012-11-13 下午3:00:42
 * @version v1.0
 * @Other :@see #Files
 */
@Controller
@RequestMapping("/adminback")
public class MemberWeb extends BuyTools {

	@Resource
	private CommonsServiceClient commons = null;

	@RequestMapping("/adminLogin.form")
	public String adminLogin() {
		return this.getWebProperties("web", "adminlogin.page");
	}

	@RequestMapping("/adminForgetpwd.form")
	public String adminForgetpwd() {
		return this.getWebProperties("web", "adminlogin.forgetpwd.page");
	}

	@RequestMapping("/adminExit.form")
	public String exit(HttpSession session) {
		int who = 0;
		if (session != null) {
			CmiAdminUser user = ((CmiAdminUser) session.getAttribute("loginAdmin")).clone();
			who = user.getUuid();
			session.removeAttribute("loginAdmin");
			session.invalidate();
			session = null;
			commons.noteAdminLog(this.getWebProperties("web", "adminlogin.exitinfo"), who);
		}
		return this.getWebProperties("web", "adminlogin.page");
	}

	@RequestMapping("/dispatch.adm")
	public ModelAndView jumpIndex(HttpSession session, @RequestParam("p") String p,
			@RequestParam("menuId") String menuId) {
		ModelAndView mv = new ModelAndView();
		// 获取登录人信息
		CmiAdminUser user = ((CmiAdminUser) session.getAttribute("loginAdmin")).clone();

		// 设置跳转到的页面
		if (p.startsWith("http://")) {
			mv.setViewName("redirect:" + p);
		} else {
			if (p.endsWith(".jsp")) {
				p = p.substring(0, p.lastIndexOf(".jsp"));
			}
			mv.setViewName(p);
		}
		// 加装菜单的操作功能按钮function
		String sql = "";
		String toolbars = "[]";
		Object[] args = new Object[0];
		try {
			if (user.getPower() == 1) {
				args = new Object[]{menuId};
				sql = service.getSql("sql", "admin.login.toolbar.all");
			} else {
				args = new Object[]{menuId,user.getUuid()};
				sql = service.getSql("sql", "admin.login.toolbar.user");
			}
			toolbars = toolsbox.list2JsonArrayStr(service.queryForList(sql, Toolbar.class, args));
		} catch (Exception e) {
			toolbars = "[]";
			log4j.error("load menu toolbar error..." + e);
		}
		mv.addObject("toolbars", toolbars);
		mv.addObject("menuId",menuId);
		return mv;
	}

	@ResponseBody
	@RequestMapping("/adminLogin_check.ajax")
	public String adminLogin_check(@RequestParam("u") String u, @RequestParam("p") String p,
			@RequestParam("v") String v, HttpSession session, HttpServletRequest req) {
		JSONObject json = new JSONObject();
		String res = "0";
		json.element("error", res);
		try {
			// 验证码
			String vcode = (String) session.getAttribute("vcode");
			if (!vcode.equalsIgnoreCase(v)) {
				json.element("error", "1");
				json.element("msg", this.getWebProperties("web", "adminlogin.v.error.vercode"));
			} else {
				res = service.getSql("sql", "admin.login.check");
				List<ConditionBean> beans = new ArrayList<ConditionBean>();
				beans.add(new ConditionBean("aid", "=", "?", u, null));
				beans.add(new ConditionBean("apass", "=", "?", p, null));
				CmiAdminUser ls = (CmiAdminUser) service.queryForObject(res, CmiAdminUser.class, beans);

				if (ls == null) {
					json.element("error", "2");
					json.element("msg", this.getWebProperties("web", "adminlogin.v.error.user"));
				} else {
					// 更新登陆人员信息，并写入日志
					String ip = this.getVisitorIp(req);
					Object[] args = new Object[] { ls.getAid(), ls.getAmail(), ls.getApass(), ip, ls.getUuid() };
					String doWhatMsg = this.getWebProperties("web", "adminlogin.loginfo ");
					boolean b = commons.editAdminWithLog(Commons.BackProcess.ADMIN_LOGIN, Status.MODIFY, args,
							doWhatMsg, ls.getUuid());
					if (b == false) {
						throw new Exception("SQL execute error");
					}
					session.setAttribute("loginAdmin", ls);
				}
			}
		} catch (Exception ex) {
			log4j.error(ex);
			json.element("error", "3");
			//json.element("msg", this.getWebProperties("web", "adminlogin.v.error.other"));
			json.element("msg", ex.getMessage());
		}
		return json.toString();
	}

	@ResponseBody
	@RequestMapping("/adminLogin_forgatpwd.ajax")
	public String adminLogin_forgatpwd(@RequestParam("u") String u, @RequestParam("e") String e, HttpSession session) {

		JSONObject json = new JSONObject();
		String res = "0";
		json.element("error", res);
		try {
			res = service.getSql("sql", "admin.pagin");
			List<ConditionBean> beans = new ArrayList<ConditionBean>();
			beans.add(new ConditionBean("aid", "=", "?", u, null));
			beans.add(new ConditionBean("amail", "=", "?", e, null));
			CmiAdminUser ls = (CmiAdminUser) service.queryForObject(res, CmiAdminUser.class, beans);
			if (ls == null) {
				json.element("error", "1");
				json.element("msg", this.getWebProperties("web", "adminlogin.forgetpwd.v.user "));
			} else {
				String newPwd = toolsbox.getRandomID(Integer.valueOf(this.getWebProperties("web",
						"adminlogin.forgetpwd.random.pass.length")));
				// 发送邮件信息
				String content = this.getWebProperties("web", "adminlogin.forgetpwd.mail.content");
				content = content.replace("${u}", u).replace("${p}", newPwd);
				String subject = this.getWebProperties("web", "adminlogin.forgetpwd.mail.subject");

				if (!commons.sendEmail(subject, content, e)) {
					throw new Exception("AdminMail Send Error!");
				} else {
					// 更新需要修改密码人员的密码为随机生成的密码
					Object[] args = new Object[] { service.MD5Encode(newPwd), ls.getUuid() };
					String sql = commons.getEnumSql(Commons.BackProcess.ADMIN_FORGETPWD, Status.MODIFY);
					service.executeSQL(sql, args);
				}
			}
		} catch (Exception e1) {
			log4j.error(e1);
			json.element("error", "2");
			json.element("msg", this.getWebProperties("web", "adminlogin.forgetpwd.v.exception"));
		}
		return json.toString();
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/roleEditPage.form")
	public ModelAndView roleEditPage(@RequestParam("qr") String qr,@RequestParam("menuId") String menuId,@RequestParam("dt") String dt) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName(this.getWebProperties("web", "cmi_power.role_edit.page"));
		JSONObject error = new JSONObject();
		
		Commons.BackProcess e = Commons.BackProcess.ADMIN_POWER_CMI_ROLE;
		List<Tree> business = new ArrayList<Tree>();
		List<Tree> power = new ArrayList<Tree>();
		String datas = "";
		//加载系统内的业务菜单
		try {
			try {
				datas = toolsbox.encoding2GBK(dt);
			} catch (UnsupportedEncodingException e1) {
				datas = dt;
			}
			List<ConditionBean> beans = (List<ConditionBean>) this.toolsbox.jsonArraystr2List(qr,ConditionBean.class);
			Object[] args = new Object[0];
			business = commons.queryTree(e, Status.TREE, beans, args);
			if(dt.trim().length() > 0) {
				CmiRole role = (CmiRole) toolsbox.jsonstr2Object(dt, CmiRole.class);
				power = commons.queryTree(Commons.BackProcess.ADMIN_POWER_CMI_ROLE_POWER, Status.TREE, beans, role.getUuid());
			}
			error.element("code", "0");
		} catch (AzjQueryBuilderException e1) {
			error.element("code", "1");
			business = new ArrayList<Tree>();
			power = new ArrayList<Tree>();
		}
		//返回
		error.element("business", toolsbox.list2JsonArrayStr(business));
		error.element("power", toolsbox.list2JsonArrayStr(power));
		error.element("menuId",menuId);
		error.element("dt",datas);
		//参数
		mv.addObject("error", error);
		return mv;
	}

	public void setCommons(CommonsServiceClient commons) {
		this.commons = commons;
	}

}
